/**
 * Created by chengming on 18/5/27.
 * version 1.0
 */
const BaseJsonAdapter = require('../base/BaseJsonAdapter');
const ArticleHrefAdapter = require('../ArticleHrefAdapter');
const iconv = require("iconv-lite");
const vm = require('vm');
const request = require('request-promise');
const logger = require('../../conf/logger');
const querystring = require("querystring")
const cheerio = require('cheerio');
const urlTool = require('url');
const urldecode = require('urlencode')

/**
 * 港交所-上市公司公告
 * @type {module.Bjp2p}
 */
module.exports = class Szse extends ArticleHrefAdapter {


    initWinEnv(){
        global.window = {
            innerWidth:1232,
            innerHeight:632,
            screenX:11,
            screenY:22,
            screen:{
                width:1280,
                height:800
            }
        };

        global.document = {
            documentElement:{
                clientWidth:1217,
                clientHeight:550
            },
            body:{
                clientWidth:1217,
                clientHeight:1467
            },
            _cookie: [],

            get cookie(){
                return this._cookie;
            },

            set cookie(val){
                this._cookie.push(val);
            }
        };
    }

    async doRequest(){

        //初始化窗口属性
        this.initWinEnv();

        return await super.doRequest();
    }

    parseHtml(html, linkRule) {
        //将解析后的内容加载进解析器
        let $ = cheerio.load(html);
        let contents = [];
        let that = this;
        let rangeText = '';
        let encoding = this.encoding;
        $(this.linkRule).each(function () {
                let scriptStr = $(this).html();
                if(scriptStr.indexOf('curTitle')>-1) {
                    scriptStr=scriptStr.replace(/<script>/g,'');
                    scriptStr=scriptStr.replace(/<\/script>/g,'');
                    scriptStr = scriptStr.substr(0,scriptStr.indexOf('var docType'));
                    vm.runInThisContext(scriptStr);
                    let title = curTitle;
                    let href = curHref;
                    href = urlTool.resolve(that.requestUrl, curHref);

                    if (title.length != 0 || href.length != 0) {
                        contents.push({
                            title: title,
                            href: href
                        });
                        rangeText += title + href;
                    }
                }


        });

        return {
            rangeText: rangeText,
            contents: contents
        };
    }


}
